#include "qt_node/qt_ros_node.hpp"
#include <QDebug>

QtROSNode::QtROSNode(const std::string &node_name, QObject *parent)
    : QObject(parent), Node(node_name)
{
    rclcpp::PublisherOptions pub_options;
    pub_options.use_intra_process_comm = rclcpp::IntraProcessSetting::Enable;
    publisher_ = this->create_publisher<std_msgs::msg::String>("qt_topic", 10, pub_options);

    rclcpp::SubscriptionOptions sub_options;
    sub_options.use_intra_process_comm = rclcpp::IntraProcessSetting::Enable;
    subscription_ = this->create_subscription<std_msgs::msg::String>(
        "qt_topic", 10, std::bind(&QtROSNode::topic_callback, this, std::placeholders::_1),sub_options);

    // 初始化并配置定时器
    m_ros_timer = new QTimer(this); // 'this'作为父对象，保证在同一线程并自动管理内存
    connect(m_ros_timer, &QTimer::timeout, this, &QtROSNode::spin_some);
    //  只创建和连接，不启动！

    RCLCPP_INFO(this->get_logger(), "QtROSNode has been initialized with a 100ms spin timer.");
}

QtROSNode::~QtROSNode()
{
    RCLCPP_INFO(this->get_logger(), "QtROSNode is shutting down.");
}

void QtROSNode::startTimer()
{
    m_ros_timer->start(100);
    RCLCPP_INFO(this->get_logger(), "ROS spin timer started in thread.");
}

// 实现 spin_some 槽
void QtROSNode::spin_some()
{
    // 非阻塞地处理所有当前挂起的ROS事件
    rclcpp::spin_some(this->get_node_base_interface());
}

void QtROSNode::publishMessage(const QString &msg)
{
    auto message = std_msgs::msg::String();
    message.data = msg.toStdString();
    RCLCPP_INFO(this->get_logger(), "Publishing: '%s'", message.data.c_str());
    publisher_->publish(message);
}

void QtROSNode::topic_callback(const std_msgs::msg::String::SharedPtr msg)
{
    RCLCPP_INFO(this->get_logger(), "I heard: '%s'", msg->data.c_str());
    emit messageReceived(QString::fromStdString(msg->data));
}
